package com.icode.service.impl.management;

import com.icode.core.dto.house.HouseWeekDTO;
import com.icode.core.dto.house.HouseWeekTimeDTO;
import com.icode.core.dto.house.RentDTO;
import com.icode.core.model.house.*;
import com.icode.core.model.manage.Reserve;
import com.icode.core.model.manage.ReserveTime;
import com.icode.core.model.user.User;
import com.icode.core.shared.RentHandle;
import com.icode.dao.RentDao;
import com.icode.dao.ReserveDao;
import com.icode.service.management.RentService;
import com.icode.service.user.MessageService;
import org.joda.time.LocalDate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: sunk
 * Date: 15-11-6
 * Time: 下午6:41
 * To change this template use File | Settings | File Templates.
 */
@Service("rentService")
@Transactional
public class RentServiceImpl implements RentService {

    @Autowired
    private RentDao rentDao;
    @Autowired
    private MessageService messageService;
    @Autowired
    private ReserveDao reserveDao;

    @Override
    public List<RentDTO> findMyHouseByStatus(MyHouseStatus toRent, String type) {
        ProductType productType = ProductType.valueOf(type);
        List<Rent> rents = rentDao.findMyHouseByStatus(toRent, productType);
        List<RentDTO> rentDTOs = RentDTO.toDTOs(rents);
        return rentDTOs;
    }

    @Override
    public List<RentDTO> findMyHouseByStatusNoType(MyHouseStatus toRent) {
        List<Rent> rents = rentDao.findMyHouseByStatusNoType(toRent);
        List<RentDTO> rentDTOs = RentDTO.toDTOs(rents);
        return rentDTOs;
    }

    @Override
    public boolean handleRent(RentDTO rentDTO) {
        boolean isSuccess = true;
        try {
            Integer.valueOf(rentDTO.getPrice());
        } catch (NumberFormatException e) {
            return false;
        }
        String myHouseGuid = rentDTO.getMyHouseGuid();
        MyHouse myHouse = rentDao.findByGuid(MyHouse.class, myHouseGuid);
        HouseWeekTime houseWeekTime = rentDao.findByGuid(HouseWeekTime.class, rentDTO.getDays());
        HouseWeekTimeDTO houseWeekTimeDTO = HouseWeekTimeDTO.toDTO(houseWeekTime);
        ReserveTime reserveTime = reserveDao.findReserveTimeByHouseWeekTime(houseWeekTime);
        if (!reserveTime.status().equals(MyHouseStatus.ACTIVITY)) {
            isSuccess = false;
            return isSuccess;
        }
        String checkInDateAsString = houseWeekTimeDTO.getStart();
        LocalDate checkInDate = new LocalDate(checkInDateAsString);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Integer currentDays =0;
        try {
            long m = sdf.parse(houseWeekTimeDTO.getEnd()).getTime() - sdf.parse(houseWeekTimeDTO.getStart()).getTime();
            currentDays = (int) (m / (1000 * 60 * 60 * 24));
            rentDTO.setDays(currentDays.toString());
        } catch (ParseException e) {
            isSuccess = false;
            return isSuccess;
        }
//        int allDays = currentDays;
//        int totalDays = myHouse.days();
//        if (!rents.isEmpty()) {
//            Iterator<Rent> iterator = rents.iterator();
//            while (iterator.hasNext()) {
//                Rent next = iterator.next();
//                int days = Integer.valueOf(next.days());
//                allDays += days;
//                checkInDate = new LocalDate(next.leaveDate());
//            }
//        }
 //       int judgeDays = totalDays + currentDays;
//        if (judgeDays > 7) {
//            isSuccess = false;
//        } else {
        LocalDate currentCheckInDate = checkInDate;
        LocalDate currentLeaveDate = checkInDate.plusDays(currentDays);
        //   myHouse.updateStatus(MyHouseStatus.TORENT);
        //   myHouse.updateDays(judgeDays);
        Rent rent = rentDTO.toRent(myHouse, currentLeaveDate.toString(), currentCheckInDate.toString(), MyHouseStatus.TORENT);
        rentDao.saveOrUpdate(rent);
        reserveTime.upDateStatus(MyHouseStatus.TORENT);
//        }
        return isSuccess;
    }

    @Override
    public RentDTO findRentByGuid(String rentGuid) {
        Rent rent = rentDao.findByGuid(Rent.class, rentGuid);
        return RentDTO.toDTO(rent);
    }

    @Override
    public void update(RentDTO initRentDTO) {
        Rent rent = rentDao.findByGuid(Rent.class, initRentDTO.getGuid());
        String customer = initRentDTO.getCustomer();
        String phoneNum = initRentDTO.getPhoneNum();
        String description = initRentDTO.getDescription();
        String coustomerNum = initRentDTO.getCoustomerNum();
        boolean noticeWay = initRentDTO.isNoticeWay();
        rent.update(customer, phoneNum, description, coustomerNum, noticeWay);
    }

    @Override
    public List<RentDTO> findMyHouseByCondition(String area, String week, String theme, String price) {
        area = RentHandle.initAreaHql(area);
        price = RentHandle.initPriceHql(price);
        theme = RentHandle.initThemeHql(theme);
        List<Rent> rents;
        MyHouseStatus status = MyHouseStatus.TORENT;
        ProductType houseBase = ProductType.HOUSEBASE;
        ProductType apartment = ProductType.APARTMENT;
        if (StringUtils.isEmpty(area) && StringUtils.isEmpty(price) && StringUtils.isEmpty(theme) && week.equals("不限")) {
            rents = rentDao.findRentsByStatus(status, houseBase, apartment);
        } else {
            rents = rentDao.findMyHouseByParams(status, area, week, price, theme, houseBase, apartment);
        }
        List<RentDTO> rentDTOs = new ArrayList<>();
        for (Rent rent : rents) {
            RentDTO rentDTO = RentDTO.toDTO(rent);
            rentDTOs.add(rentDTO);
        }
        return rentDTOs;
    }

    @Override
    public void payFor(RentDTO rentDTO) {
        Rent rent = rentDao.findByGuid(Rent.class, rentDTO.getGuid());
        String customer = rentDTO.getCustomer();
        String coustomerNum = rentDTO.getCoustomerNum();
        String phoneNum = rentDTO.getPhoneNum();
        String description = rentDTO.getDescription();
        boolean noticeWay = rentDTO.isNoticeWay();
        rent.update(customer, phoneNum, description, coustomerNum, noticeWay);
    }

    @Override
    public List<RentDTO> findRentAllByPage(String currentPage, String status) {
        List<Rent> rents = rentDao.findRentAllByPage(currentPage, status);
        List<RentDTO> rentDTOs = new ArrayList<>();
        if (rents != null) {
            rentDTOs = RentDTO.toDTOs(rents);
        }
        return rentDTOs;
    }

    @Override
    public List<RentDTO> findRentForHirer(User user) {
        List<Rent> rents = rentDao.findRentForHirer(user);
        return RentDTO.toDTOs(rents);
    }

    @Override
    public List<RentDTO> findRentForLessee(User user) {
        List<Rent> rents = rentDao.findRentForLessee(user);
        return RentDTO.toDTOs(rents);
    }

    @Override
    public String updateRent(User user, String rentGuid) {
        Rent rent = rentDao.findByGuid(Rent.class, rentGuid);
        rent.update(user, MyHouseStatus.RENTING);
        return rent.myHouse().guid();
    }

    @Override
    public void sentRentSuccess(String out_trade_no) {
        Rent rent = rentDao.findByGuid(Rent.class, out_trade_no);
        RentDTO rentDTO = RentDTO.toDTO(rent);
        messageService.sendRentSuccess(rentDTO);
    }

    @Override
    public List<RentDTO> findRentByUsername(String username) {
        List<Rent> rents = rentDao.findRentByUsername(username);
        List<RentDTO> rentDTOs = new ArrayList<>();
        if (rents != null){
            rentDTOs = RentDTO.toDTOs(rents);
        }
        return rentDTOs;
    }

    @Override
    public List<RentDTO> findRentByCustomer(String customer) {
        List<Rent> rents = rentDao.findRentByCustomer(customer);
        List<RentDTO> rentDTOs = new ArrayList<>();
        if (rents != null){
            rentDTOs = RentDTO.toDTOs(rents);
        }
        return rentDTOs;
    }
}
